package com.work.rochegroupproperty.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.work.rochegroupproperty.dto.SearchTodoRequest;
import com.work.rochegroupproperty.dto.UpdateStatusRequest;
import com.work.rochegroupproperty.dto.UpdateTodoRequest;
import com.work.rochegroupproperty.entity.Todo;
import com.work.rochegroupproperty.service.ITodolistService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/todolist")
public class TodolistController {

    @Autowired
    private ITodolistService todolistService;

    /* * 添加待办事项
     * @param todo 待办事项对象
     * @return 是否添加成功
     */
    @PostMapping("/add")
    public boolean addTodo(@Valid @RequestBody Todo todo) {
        if(todo.getId() != null) {
            return false;
        }
        return todolistService.save(todo);
    }

    /* *
     * 获取指定ID的待办事项
     * @param id 待办事项ID
     * @return 待办事项对象
     */
    @GetMapping("/getByToDoId/{id}")
    public ResponseEntity<Todo> getTodoById(@PathVariable Integer id) {
        Todo todo = todolistService.getById(id);
        if (todo != null) {
            return ResponseEntity.ok(todo);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    /* *
        * 删除指定ID的待办事项
        * @param id 待办事项ID
        * @return 是否删除成功
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteTodoById(@PathVariable Integer id) {
        boolean success = todolistService.removeById(id);
        if (success) {
            return ResponseEntity.ok("删除成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("待办事项不存在或删除失败");
        }
    }

    /* *
     * 搜索待办事项（支持分页）
     * @param req 包含 userId、keyword、page、size
     * @return 分页结果
     */
    @GetMapping("/search")
    public IPage<Todo> searchTodos(SearchTodoRequest req) {
        return todolistService.searchTodos(req);
    }
    /* *
    * 更新待办事项(整个待办事项对象)
    * @param todo 待办事项对象
    * @return 是否更新成功
     */
    @PutMapping("/update/{id}")
    public ResponseEntity<?> updateTodo(@PathVariable Integer id,
            @Valid @RequestBody UpdateTodoRequest dto,
            BindingResult br) {

        if (br.hasErrors()) {
            // 可以返回所有校验错误信息
            return ResponseEntity.badRequest()
                    .body(br.getAllErrors());
        }

        Todo existing = todolistService.getById(id);
        if (existing == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("待办事项不存在");
        }

        // 拷贝到 entity
        BeanUtils.copyProperties(dto, existing);

        boolean success = todolistService.updateById(existing);
        if (!success) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("更新失败");
        }

        // 返回最新资源
        return ResponseEntity.ok(existing);
    }

    /* *
    /* 更新待办事项（部分字段更新）
        * @param id 待办事项ID
        * @param todo 待办事项对象（只包含需要更新的字段）
        * @return 是否更新成功
        */
    @PatchMapping("/update/{id}")
    public ResponseEntity<String> updateTodoPartial(@PathVariable Integer id, @RequestBody Todo todo) {
        if (todo.getId() == null || !todo.getId().equals(id)) {
            return ResponseEntity.badRequest().body("updateTodoPartial：不规范的请求：id 不匹配");
        }

        // 检查待办事项是否存在
        Todo existing = todolistService.getById(id);
        if (existing == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("待办事项不存在");
        }

        // 更新部分字段
        if (todo.getTitle() != null) {
            existing.setTitle(todo.getTitle());
        }
        if (todo.getDescription() != null) {
            existing.setDescription(todo.getDescription());
        }
        if (todo.getPriority() != null) {
            existing.setPriority(todo.getPriority());
        }
        if (todo.getStatus() != null) {
            existing.setStatus(todo.getStatus());
        }
        if(todo.getDueDate() != null) {
            existing.setDueDate(todo.getDueDate());
        }

        boolean success = todolistService.updateById(existing);
        return success
                ? ResponseEntity.ok("更新成功")
                : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("更新失败");
    }

    /* *
     * 获取指定用户的待办事项列表
     *
     * @param id 用户ID
     * @return 待办事项列表
     */
    @GetMapping("/user/{id}/todos")
    public List<Todo> getTodoListByBelongingUserId(@PathVariable Integer id) {
        QueryWrapper<Todo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("belonging_user_id", id);
        return todolistService.list(queryWrapper);
    }

    /* *  更新待办事项状态
     * @param request 更新请求对象
     * @return 是否更新成功
     */
    @PutMapping("/updateStatus")
    public ResponseEntity<String> updateTodoStatus(@RequestBody UpdateStatusRequest request) {
        if (request.getId() == null || request.getStatus() == null) //  校验 id 和 status 是否为空
        {
            return ResponseEntity.badRequest().body("updateTodoStatus：不规范的请求：id 和 status 存在null");
        }


        boolean validStatus = false;
        for (Todo.TodoStatus s : Todo.TodoStatus.values()) {// 校验 string status是否在枚举中
            if (s.getDbValue().equals(request.getStatus())) {
                validStatus = true;
                break;
            }
        }

        if (!validStatus) {
            return ResponseEntity.badRequest().body("updateTodoStatus：非法的状态值：" + request.getStatus());
        }

        // 更新数据库
        Todo todo = new Todo();
        todo.setId(request.getId());
        todo.setStatus(request.getStatus());

        boolean success = todolistService.updateById(todo);

        return success
                ? ResponseEntity.ok("更新成功")
                : ResponseEntity.status(HttpStatus.NOT_FOUND).body("待办事项不存在或更新失败");
    }
    /* *
        * 更新待办事项优先级
        * @param todo 待办事项对象
        * @return 是否更新成功
     */
    @PutMapping("/updatePriority")
    public ResponseEntity<String> updateTodoPriority(@RequestBody Todo todo) {
        if (todo.getId() == null || todo.getPriority() == null) {
            return ResponseEntity.badRequest().body("updateTodoPriority：不规范的请求：id 和 priority 存在null");
        }

        if (todo.getPriority() < 1 || todo.getPriority() > 5) {
            return ResponseEntity.badRequest().body("updateTodoPriority：优先级必须在1到5之间");
        }

        // 更新数据库
        boolean success = todolistService.updateById(todo);

        return success
                ? ResponseEntity.ok("更新成功")
                : ResponseEntity.status(HttpStatus.NOT_FOUND).body("待办事项不存在或更新失败");
    }


}